//
//  MyDeviceViewController.m
//  steamRoom
//
//  Created by 安建伟 on 2019/7/1.
//  Copyright © 2019 com.thingcom. All rights reserved.
//

#import "MyDeviceViewController.h"
#import "DeviceListViewCell.h"
#import "ConnectNetController.h"
#import "APConnectNetController.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "ReactRootViewManager.h"

NSString *const CellIdentifier_DeviceList = @"CellID_DeviceList";
static float HEIGHT_CELL = 50.f;
static float HEIGHT_HEADER = 40.f;

@interface MyDeviceViewController () <UITableViewDelegate, UITableViewDataSource, GizWifiSDKDelegate>

///@brife ui和功能各模块
@property (strong, nonatomic) UIImageView *deviceImageView;
@property (strong, nonatomic) UIButton *addButton;
@property (nonatomic, strong) UITableView *deviceTable;
@property (nonatomic, strong) NSArray *deviceArray;

@end

@implementation MyDeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.layer.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1].CGColor;
    [self setNavItem];
    self.deviceImageView = [self deviceImageView];
    self.addButton = [self addButton];
    self.deviceTable = [self deviceTable];
    self.deviceTable.hidden = YES;
    //RN页面预加载
    NSString *pageName = @"myapp";
    [[ReactRootViewManager manager] preLoadRootViewWithName:pageName];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self.rdv_tabBarController setTabBarHidden:NO animated:YES];
    GizManage *manager = [GizManage shareInstance];
    [GizWifiSDK sharedInstance].delegate = self;
    [[GizWifiSDK sharedInstance] getBoundDevices:manager.uid token:manager.token];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //[self.rdv_tabBarController setTabBarHidden:YES animated:YES];
    self.navigationController.navigationBar.hidden = YES;
}

#pragma mark - Lazy load

- (void)setNavItem{
    self.navigationItem.title = LocalString(@"我的设备");
    
    UIButton *addButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,40,40)];
    [addButton setImage:[UIImage imageNamed:@"ic_nav_addDevice"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(goNetAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithCustomView:addButton];
    self.navigationItem.rightBarButtonItem= rightBarButton;
    
}

- (UIImageView *)deviceImageView{
    if (!_deviceImageView) {
        _deviceImageView = [[UIImageView alloc] initWithFrame:CGRectMake(60, 300, yAutoFit(190.f), yAutoFit(180.f))];
        _deviceImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"net_device"]];
        [self.view addSubview:_deviceImageView];
        
        [_deviceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(yAutoFit(190.f),yAutoFit(180.f)));
            make.centerX.equalTo(self.view.mas_centerX);
            make.centerY.equalTo(self.view.mas_centerY);
        }];
    }
    return _deviceImageView;
}

- (UIButton *)addButton{
    if (!_addButton) {
        _addButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addButton setTitle:LocalString(@"暂无设备，请添加") forState:UIControlStateNormal];
        [_addButton.titleLabel setFont:[UIFont systemFontOfSize:17.f]];
        [_addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_addButton setBackgroundImage:[UIImage imageNamed:@"background_Btn_login"] forState:UIControlStateNormal];
        _addButton.contentMode = UIViewContentModeScaleAspectFit;
        [_addButton addTarget:self action:@selector(goNetAction) forControlEvents:UIControlEventTouchUpInside];
        _addButton.enabled = YES;
        [self.view addSubview:_addButton];
        [_addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(yAutoFit(280.f), 60));
            make.top.equalTo(self.deviceImageView.mas_bottom).offset(yAutoFit(10.f));
            make.centerX.mas_equalTo(self.view.mas_centerX);
        }];
        
    }
    return _addButton;
}

- (UITableView *)deviceTable{
    if (!_deviceTable) {
        _deviceTable = ({
            UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth,ScreenHeight) style:UITableViewStylePlain];
            tableView.backgroundColor = [UIColor clearColor];
            tableView.dataSource = self;
            tableView.delegate = self;
            tableView.separatorColor = [UIColor clearColor];
            [tableView registerClass:[DeviceListViewCell class] forCellReuseIdentifier:CellIdentifier_DeviceList];
            [self.view addSubview:tableView];
            tableView.estimatedRowHeight = 0;
            tableView.estimatedSectionHeaderHeight = 0;
            tableView.estimatedSectionFooterHeight = 0;
            tableView.scrollEnabled = NO;
            tableView;
        });
    }
    return _deviceTable;
}

#pragma mark - uitableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.deviceArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return HEIGHT_CELL;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return HEIGHT_HEADER;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DeviceListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier_DeviceList];
    if (cell == nil) {
        cell = [[DeviceListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier_DeviceList];
    }
    GizWifiDevice *device = _deviceArray[indexPath.row];
    cell.deviceName.text = device.productName;
    
    if (device.netStatus == GizDeviceOnline || device.netStatus == GizDeviceControlled) {
        cell.deviceImage.image = [UIImage imageNamed:@"icon_device_left"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.deviceImage.image = [UIImage imageNamed:@"common_device_lan_offline.png"];
    }
    return cell;
}
//左滑删除 设备绑定
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:LocalString(@"delete") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NSLog(@"点击了删除");
        GizWifiDevice *device = self.deviceArray[indexPath.row];
        //提示框
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:LocalString(@"Are you sure to delete ?")preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:LocalString(@"OK") style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
            NSLog(@"action = %@",action);
            GizManage *manager = [GizManage shareInstance];
            [[GizWifiSDK sharedInstance] unbindDevice:manager.uid token:manager.token did:device.did];
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:LocalString(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
            [self.navigationController popToRootViewControllerAnimated:YES];
            NSLog(@"action = %@",action);
        }];
        [alert addAction:okAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }];
    return @[deleteAction];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    editingStyle = UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GizWifiDevice *device = _deviceArray[indexPath.row];
    [[GizManage shareInstance] setGizDevice:device];
    
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = [[ReactRootViewManager manager] rootViewWithName:@"myapp"];
    //[self.navigationController pushViewController:vc animated:YES];
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - Giz delegate
// 设备解绑实现回调
- (void)wifiSDK:(GizWifiSDK *)wifiSDK didUnbindDevice:(NSError *)result did:(NSString *)did {
    if(result.code == GIZ_SDK_SUCCESS) {
        // 解绑成功
        NSLog(@"解绑成功");
    } else {
        // 解绑失败
        NSLog(@"解绑失败");
    }
}

- (void)wifiSDK:(GizWifiSDK *)wifiSDK didDiscovered:(NSError *)result deviceList:(NSArray<GizWifiDevice *> *)deviceList{
    // 提示错误原因
    if(result.code != GIZ_SDK_SUCCESS) {
        NSLog(@"result--- %@", result.localizedDescription);
    }
    
    [self refreshTableView:deviceList];
}

#pragma mark - Actions

- (void)goNetAction {
    //显示弹出框列表选择
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* goAction = [UIAlertAction actionWithTitle:LocalString(@"一键配置") style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        //响应事件
        ConnectNetController * connectVC = [[ConnectNetController alloc] init];
        [self.navigationController pushViewController:connectVC animated:YES];
        
    }];
    
    UIAlertAction* hotAction = [UIAlertAction actionWithTitle:LocalString(@"热点配置") style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        //响应事件
        APConnectNetController * apConnectVC = [[APConnectNetController alloc] init];
        [self.navigationController pushViewController:apConnectVC animated:YES];
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:LocalString(@"取消") style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:goAction];
    [alert addAction:hotAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)refreshTableView:(NSArray *)deviceListArray{
    NSLog(@"设备数量%lu",(unsigned long)deviceListArray.count);

    NSMutableArray *deviceArray = [[NSMutableArray alloc] init];
    GizManage *manager = [GizManage shareInstance];
    for (GizWifiDevice *device in deviceListArray) {
        if (device.isBind) {
            NSLog(@"绑定设备%@",device.productName);
        }
        if (device.netStatus == GizDeviceOnline && device.isBind) {
            [deviceArray addObject:device];
        
        }
        manager.device = device;
    }
    if (deviceListArray.count >0 && manager.device.isBind) {
        _deviceTable.hidden = NO;
        _deviceImageView.hidden = YES;
        _addButton.hidden = YES;
    }else{
        _deviceTable.hidden = YES;
        _deviceImageView.hidden = NO;
        _addButton.hidden = NO;
    }
    self.deviceArray = deviceArray;
    [self.deviceTable reloadData];
}

@end
